package myorg.myrpc.thrift;

import static com.google.common.base.Preconditions.*;

import java.lang.reflect.Proxy;
import myorg.myrpc.CommonConstant;
import myorg.myrpc.IMyrpc;
import net.gdface.thrift.ClientFactory;
import net.gdface.utils.Delegator;

/**
 * client端便利性扩展工具类
 * @author guyadong
 *
 */
public class ClientExtendTools implements CommonConstant{
	private final IMyrpc syncInstance;
	private final IMyrpcThriftClientAsync asyncInstance;
	private final ClientFactory factory;
	ClientExtendTools(IMyrpc syncInstance) {
		super();
		this.syncInstance = checkNotNull(syncInstance,"syncInstance is null");
		this.asyncInstance = null;
		this.factory = unwrap(syncInstance,IMyrpcThriftClient.class).getFactory();
	}
	ClientExtendTools(IMyrpcThriftClientAsync asyncInstance) {
		super();
		this.syncInstance = null;
		this.asyncInstance = checkNotNull(asyncInstance,"asyncInstance is null");
		this.factory = asyncInstance.getFactory();
	}
	public ClientFactory getFactory() {
		return factory;
	}
	private static <T>T unwrap(Object value,Class<T> clazz){
		if(Proxy.isProxyClass(value.getClass())){
			return unwrap(Proxy.getInvocationHandler(value),clazz);
		}else if(value instanceof Delegator){
			return unwrap(((Delegator<?>)value).delegate(),clazz);
		}
		return clazz.cast(value);
	}
}
